import cloud from '@lafjs/cloud'
const db = cloud.mongo.db
let year
let startOfYear
let endOfYear

export default async function (ctx: FunctionContext) {
  let date = ctx.body.date
  year = cloud.utils.dateTimeFormat(date, 'year')
  startOfYear = new Date(year, 0, 1).getTime(); // 该年份的开始时间戳
  endOfYear = new Date(year, 11, 31, 23, 59, 59, 999).getTime(); // 该年份的结束时间戳

  //本年度开票总金额
  let array = await db.collection("invoicing").find({ add_time: { $exists: true } }).toArray()
  for (let index = 0; index < array.length; index++) {
    const element = array[index];
    await cloud.utils.updateData("invoicing", { _id: element._id, _add_time: element.add_time })
  }

  let bb = await db.collection("invoicing").find({ _add_time: { $gte: startOfYear, $lt: endOfYear } }).toArray()
  let invoicingTotal = 0
  bb.forEach(element => {
    invoicingTotal += Number(element.detailParam[0].je)
  });

  //订单总金额
  let orders = []
  //没有标记，正常的订单
  let orders1 = await db.collection("web-order").find({
    _add_time: { $gte: startOfYear, $lt: endOfYear },
    status: { $in: [2, 7, 10] },
    statisticsYear: { $exists: false }
  }).project({ displayPrice: 1 }).toArray()

  //有标记的订单
  let orders2 = await db.collection("web-order").find({
    statisticsYear: {
      $exists: true,   // 判断属性存在[1,2](@ref)
      $eq: Number(year)        // 验证值等于2025[5](@ref)
    },
    status: { $in: [2, 7, 10] },
  }).project({ displayPrice: 1 }).toArray()
  orders = [...orders1, ...orders2]

  let orderTotal = 0
  orders.forEach(element => {
    orderTotal += Number(element.displayPrice)
  });

  //开班数据 全部班级数量
  let openClass = []
  let conformToClass = [] //符合的班级id
  let classList = await db.collection("admin-class").find({
    classOpeningTime: { $regex: year.toString(), $options: "i" }
  }).toArray()
  classList.forEach(element => {
    if (element.status == 1) openClass.push(element)
    conformToClass.push(element._id)
  });

  //获证情况
  let hasCert = []
  //获证的分母，是订单里面的课程是需要统计的
  let curriculumIds = await getCertificationOrders()

  let certificationStatus = await db.collection("admin-class-student").find({
    userState: 1,
    classId: { $in: conformToClass },
    orderId: { $in: curriculumIds }
  }).toArray()
  certificationStatus.forEach(element => {
    if (element.isExamination && (element.isExamination == 1)) {
      hasCert.push(element)
    }
  });

  //培训人数（正在读+已结束）
  let trainCount = await getTrainCount(classList)

  //团体学员
  let groupCount = await getGroupCount(classList)

  return cloud.utils.requestReturn({
    data: {
      invoicingTotal,
      orderTotal,
      classTotal: classList.length,
      openClassTotal: openClass.length,
      certificationTotal: certificationStatus.length,//获证学员分母
      hasCertTotal: hasCert.length,//已获证学员
      trainCount,//培训人数
      groupCount,//团体学员
    }
  })
}


//团体学员
async function getGroupCount(classList) {
  let aa = []
  classList.forEach(element => {
    aa.push(element._id)
  });
  const count = await db.collection('admin-class-student')
    .countDocuments({ classId: { $in: aa }, source: { $exists: true } })
  return count
}

//培训人数
async function getTrainCount(classList) {
  let aa = []
  classList.forEach(element => {
    aa.push(element._id)
  });
  const count = await db.collection('admin-class-student')
    .countDocuments({ classId: { $in: aa } })
  return count
}

//符合班级数量
async function getCertificationOrders() {
  let courseList = await db.collection("web-curriculum").find({
    statisticsCertification: {
      $exists: true,
      $eq: 1
    }
  }).project({ _id: 1 }).toArray()

  //全部课程
  let courseArr = await db.collection("web-course").find({}).project({ type: 1 }).toArray()

  let datas = []
  courseArr.forEach(element => {
    if (cloud.utils.isFieldEqual(courseList, "_id", element.type[0])) datas.push(element._id)
  });

  //正常年份的订单
  let orders1 = await db.collection("web-order").find({
    _add_time_str: { $regex: year.toString(), $options: "i" },
    status: { $in: [2, 7, 10] },
    curriculum_id: { $in: datas }
  }).project({ _id: 1 }).toArray()
  console.log("正常年份的订单", orders1.length)

  //有延期标识的订单
  let orders2 = await db.collection("web-order").find({
    status: { $in: [2, 7, 10] },
    curriculum_id: { $in: datas },
    statisticsYear: {
      $exists: true,   // 判断属性存在[1,2](@ref)
      $eq: Number(year)        // 验证值等于2025[5](@ref)
    },
  }).project({ _id: 1 }).toArray()
  console.log("有几个延期", orders2.length)


  let orders = [...orders1, ...orders2]
  console.log("符合的订单", orders.length)

  let list = []
  orders.forEach(element => {
    list.push(element._id)
  });
  return list

}